package com.twosnail.frame.model;

import com.jfinal.log.Logger;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.twosnail.frame.commin.util.ApiUitl.HttpXmlUtils;
import com.twosnail.frame.commin.util.ApiUitl.MD5Tools;
import com.twosnail.frame.commin.util.ApiUitl.ParaUitl;
import org.apache.commons.lang.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by yangcs on 2017/7/24.
 */
public class WxUserAccoutLog extends Model<WxUserAccoutLog> {

    private Logger logger = Logger.getLogger(WxUserAccoutLog.class) ;
    public static final WxUserAccoutLog me = new WxUserAccoutLog() ;
    public static final String url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";//url
    public static final String mch_appid = "wx4c3837e5f3f8a6e7";//appid
    public static final String mchid = "1484443412";//商户号
    public static final String key = "8954e7a12453e97967ef794ca7b0579d";//密钥

    /**
     * 获取登录用户下所有流水
     */
    public Page<Record> getAllUser(int pageNumber, int pageSize, String  keyWord){
        StringBuffer sb = new StringBuffer(" from wx_user a ");
        if( keyWord != null && !"".equals( keyWord = keyWord.trim() ) ) {
            sb.append( " where (a.mobile LIKE '%"+keyWord+"%' or a.name LIKE '%"+keyWord+"%')" ) ;
        }
        sb.append(" order by cz desc");
        return Db.paginate(pageNumber, pageSize,
                "select a.headImg,a.mobile,a.name,a.rtDate,a.permission,a.sex,a.wxUserId,a.accout, " +
                        "( SELECT IFNULL(SUM(accout),0) FROM wx_user_accout_log WHERE wxUserId = a.wxUserId AND type = 1 ) cz, " +
                        "( SELECT IFNULL(SUM(accout),0) FROM wx_user_accout_log WHERE wxUserId = a.wxUserId AND type = 3 ) - ( SELECT IFNULL(SUM(accout), 0) FROM wx_user_accout_log WHERE wxUserId = a.wxUserId AND type = 5 ) xf, " +
                        "( SELECT IFNULL(SUM(accout),0) FROM wx_user_accout_log WHERE wxUserId = a.wxUserId AND type = 2 ) tx " , sb.toString() );
    }

    /**
     * 根据类型查询金额
     * @param type
     * @return
     */
    public BigDecimal getTotal(Integer type){
        return Db.queryBigDecimal("select IFNULL(SUM(accout),0) from wx_user_accout_log where type = ?",type);
    }

    /**
     * 流水
     * @param pageNumber
     * @param pageSize
     * @param userId
     * @return
     */
    public Page<Record> getLogList(int pageNumber, int pageSize, long userId){
        StringBuffer sb = new StringBuffer(" from wx_user_accout_log a where a.wxUserId = "+userId +" order by a.createTime desc ");
        return Db.paginate(pageNumber, pageSize,"select a.type,FROM_UNIXTIME(a.createTime/1000, '%Y-%m-%d %H:%i:%S')createTime,a.accout ", sb.toString() );
    }

    /**
     * 提现列表数据
     * @param pageNumber
     * @param pageSize
     * @return
     */
    public Page<Record> getTxList(int pageNumber, int pageSize){
        StringBuffer sb = new StringBuffer(" from wx_user_accout_log a LEFT JOIN wx_user b ON a.wxUserId = b.wxUserId where a.type = 7 and done = 0 order by a.createTime desc ");
        return Db.paginate(pageNumber, pageSize,"select b.name,FROM_UNIXTIME(a.createTime/1000, '%Y-%m-%d %H:%i:%S')createTime,a.accout,a.wxUserId,a.logId ", sb.toString() );
    }

    /**
     * 提现
     * @param logId
     * @param accout
     * @param wxUserId
     * @return
     */
    public boolean tx(Long logId , Double accout, Long wxUserId){
        WxUser user = WxUser.me.getWxUser(wxUserId);
        if( user != null ){
            Map<String,Object> paraMap = new HashMap<String,Object>();
            paraMap.put("mch_appid",mch_appid);
            paraMap.put("mchid",mchid);
            paraMap.put("openid",user.getStr("wxName"));
            paraMap.put("nonce_str", System.currentTimeMillis());
            paraMap.put("partner_trade_no",System.currentTimeMillis());
            paraMap.put("check_name","NO_CHECK");
            paraMap.put("re_user_name",user.getStr("name"));
            DecimalFormat decimalFormat = new DecimalFormat("###################.###########");
            paraMap.put("amount",decimalFormat.format(accout*100));
            paraMap.put("desc","提现");
            paraMap.put("spbill_create_ip", "47.92.69.188");
            String StringA = ParaUitl.formatUrlMap(paraMap,false,false);
            System.out.println("StringA:"+StringA);
            String data = StringA + "&key="+key;
            String sign = MD5Tools.MD5(data).toUpperCase();
            System.out.println("签名sign:"+sign);
            paraMap.put("sign",sign);
            System.out.println("xml参数:"+ HttpXmlUtils.xmlInfo(paraMap));
            String weixinPost = null;
            try {
                weixinPost = HttpXmlUtils.httpsRequest(url, HttpXmlUtils.xmlInfo(paraMap),mchid).toString();
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
            System.out.println("结果:"+weixinPost);
            if(StringUtils.isNotBlank(weixinPost) && weixinPost.indexOf("FAIL") != -1 ){
                return false;
            }
            WxUserAccoutLog log = new WxUserAccoutLog();
            log.set("logId",logId);
            log.set("done",1);
            log.update();
            log = new WxUserAccoutLog();
            log.set("wxUserId",wxUserId);
            log.set("type",2);
            log.set("accout",accout);
            log.set("createTime",System.currentTimeMillis());
            log.save();
            return true;
        }
        return false;
    }
}
